<?php
namespace app\common\service;

use app\common\util\Upload;
use app\common\util\Util;
use think\Model;
use app\common\model\SystemNews;
use think\Request;
use app\common\model\TopicView;

class ArticlesService extends BaseService
{
    protected $pageSize = 10;
    
    

    /**
     * 获取文章列表（对应话题列表）
     * @param SystemNews $snModel
     * @param unknown $sid
     * @param unknown $p
     * @return unknown
     */
    public function getArticlesList(SystemNews $snModel, $sid, $catid, $p){
        $where = [
            'store_id' => $sid,
            'module_id' => 1,
            'catid' => $catid,
            'is_system' => 0,
            'status' => 1
        ];

        $offset = ($p - 1) * $this->pageSize;
        
        $articles_list = $snModel->where($where)->order('ord DESC')->limit( $offset, $this->pageSize )->select();
        
        $list = array();
        if ($articles_list){
            foreach ($articles_list as $k => $v){
                $list[$k]['id'] = $v['id'];
                $list[$k]['title'] = $v['title'];
                $list[$k]['author'] = $v['author'];
                $list[$k]['content'] = htmlspecialchars_decode($v['content']);
                $list[$k]['inputtime'] = date('Y-m-d H:i:s',$v['inputtime']);
                $list[$k]['description'] = $v['description'];
                $list[$k]['thumb'] = $v['thumb'];
                $list[$k]['pv'] = $v['pv'];
            }
        }

        return $list;
    }
    
    /**
     * 获取文章详情（对应话题详情）
     * @param unknown $artcileId
     * @return \\common\model\SystemNews
     */
    public function getArticleDetail(Request $request){
        $uid = $request->has('uid') ? $request->param('uid') : 0;
        $articleId = $request->param('article_id');
        $sid = $request->param('sid');
        
        $tvModel = new TopicView();
        
        $detail = SystemNews::get(['id' => $articleId, 'store_id' => $sid]);
        
        if (empty($detail)) {
            return false;
        }
        
        //pv量自增1
        $detail->pv += 1;
        
        //计算uv量
        if ($uid){
            $r = $tvModel->where(['topic_id' => $articleId, 'user_id' => $uid, 'store_id' => $sid])->find();
            if (empty($r)){
                $detail->uv += 1;
            }
        }
        $detail->save();
        
        $data = array();
        $data['is_share'] = $detail->data['is_share'];
        $data['id'] = $detail->data['id'];
        $data['title'] = $detail->data['title'];
        $data['author'] = $detail->data['author'];
        $data['content'] = htmlspecialchars_decode($detail->data['content']);
        $data['inputtime'] = date('Y-m-d H:i:s',$detail->data['inputtime']);
        $data['description'] = $detail->data['description'];
        $data['pv'] = $detail->data['pv'];
        $data['thumb'] = $this->domain.$detail->data['thumb'];
        
        //增加访问记录
        $tvModel->user_id = $uid;
        $tvModel->topic_id = $articleId;
        $tvModel->store_id = $sid;
        $tvModel->visit_time = time();
        $tvModel->visit_ip = $request->server('REMOTE_ADDR');
        $tvModel->save();
        
        //获取微信分享配置信息
//         $url = 'http://'.request()->server('HTTP_HOST').'/wap/html/DMShelper.html?sid='.$sid.'&uid='.$uid.'#/course/detail/'.$articleId;
//         $url = 'http://'.request()->server('HTTP_HOST').'/wap/html/DMShelper.html?sid='.$sid.'&uid='.$uid;
//         $store_weixin = $this->getShareParams($sid, $url);
//         $data['store_weixin'] = $store_weixin;
        
        return $data;
    }
    
    /**
     * 获取文章分类
     * @param int $sid
     */
    public function getCategoryList( $sid ){
        $list = db('system_columns')->field('title,cid as catid')->where(['store_id' => $sid, 'status' => 1])->order('ord DESC')->select();
        return $list;
    }


    /**
     * 获取话题列表 后台使用
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getTopicList($sid, $search, $p, $pageSize){
//        $filed = 'sc.title as category_name,sn.id,sn.title,sn.author,sn.status,sn.inputtime,sn.updatetime,sn.istop,sn.pv,sn.complaint';
        $filed = 'sc.title as category_name,sn.*';
        $where = [];
        $where['sn.store_id'] = $sid;
        $where['sn.module_id'] = 1;
        $where['sn.is_system'] = 0;
        $where['sn.status'] = ['>',-1];
        if(!empty($search)){
//            $where['sn.title|sn.author|sc.title'] = $search;
            $where['sn.title|sn.author|sc.title'] = ['like', "%$search%"];
        }
        $list_count = db()->name('system_news')
                    ->alias('sn')
                    ->join('system_columns sc','sn.catid = sc.cid','LEFT')
                    ->where($where)
                    ->count();
        $list = db()->name('system_news')
                ->alias('sn')
                ->field($filed)
                ->join('system_columns sc','sn.catid = sc.cid','LEFT')
                ->where($where)
                ->order('id DESC')
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        
        if($list){
            foreach ($list as $k => $v) {
                $list[$k]['add_time'] = $v['updatetime'] ? date('Y-m-d H:i:s',$v['updatetime']) : date('Y-m-d H:i:s',$v['inputtime']);
                $list[$k]['content'] = htmlspecialchars_decode($v['content']);
                unset($list[$k]['inputtime']);
                unset($list[$k]['updatetime']);
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 新增或修改话题
     * @param $sid
     * @param $topic_id
     * @param array $data
     * @return int|string
     * @throws \think\Exception
     */
    public function saveTopic($sid, $topic_id, $data = []){
        $save_data = [];
        $save_data['title'] = $data['title'];
        $save_data['ord'] = $data['ord'];
        $save_data['is_popularize'] = $data['is_popularize'];
        $save_data['status'] = $data['status'];
        $save_data['keywords'] = $data['keywords'] ?? '';
        $save_data['catid'] = $data['catid'] ?? 0;
        $save_data['author'] = $data['author'] ?? '';
        $save_data['thumb'] = $data['thumb'] ?? '';
        $save_data['url'] = $data['url'] ?? '';
        $save_data['description'] = $data['description'] ?? '';
        $content = $data['content'] ?? '';
        $save_data['content'] = htmlspecialchars($content);

        $save_data['module_id'] = 1;
        $save_data['is_system'] = 0;
        if($topic_id > 0){
            //更新
            $save_data['updatetime'] = time();
            return db('system_news')->where(['id' => $topic_id, 'store_id' => $sid ])->update($save_data);
        } else {
            //新增
            $save_data['inputtime'] = time();
            $save_data['updatetime'] = 0;
            $save_data['store_id'] = $sid;
            return db('system_news')->insert($save_data);
        }
    }

    /**
     * 删除话题
     * @param $sid
     * @param $topic_id
     * @param $batch(1为批量删除)
     * @return int
     */
    public function deleteTopic($sid, $topic_id, $batch = 0){
        $where = [];
        $where['store_id'] = $sid;
        $where['id'] = $batch == 1 ? ['in', $topic_id] : $topic_id;
        return db('system_news')->where($where)->setField('status',-1);
    }

    /**
     * 修改话题状态
     * @param $sid
     * @param $topic_id
     * @param $status
     * @param int $batch(1为批量修改)
     * @return int
     */
    public function changeTopicStatus($sid, $topic_id, $status, $batch = 0){
        $where = [];
        $where['store_id'] = $sid;
        $where['id'] = $batch == 1 ? ['in', $topic_id] : $topic_id;
        return db('system_news')->where($where)->setField('status',$status);
    }


    /**
     * 置顶话题
     * @param $sid
     * @param $topic_id
     * @param $istop
     * @param int $batch（1为批量修改）
     * @return int
     */
    public function topicToTop($sid, $topic_id, $istop, $batch = 0){
        $where = [];
        $where['store_id'] = $sid;
        $where['id'] = $batch == 1 ? ['in', $topic_id] : $topic_id;
        return db('system_news')->where($where)->setField('istop',$istop);
    }

    /**
     * 新增或编辑话题分类
     * @param $sid
     * @param $cid
     * @param array $data
     * @return int|string
     * @throws \think\Exception
     */
    public function saveTopicCategory($sid, $cid, $data = []){
        $save_data = [];
        $save_data['title'] = $data['title'];
        $save_data['thumb'] = $data['thumb'] ?? '';
        $save_data['description'] = $data['description'] ?? '';
        $save_data['ord'] = $data['ord'];
        $save_data['status'] = 1;
        $save_data['pid'] = 0;
        $save_data['module_id'] = 1;
        $save_data['is_system'] = 0;

        if($cid > 0){
            return db('system_columns')->where(['cid' => $cid, 'store_id' => $sid])->update($save_data);
        } else {
            $save_data['store_id'] = $sid;
            return db('system_columns')->insert($save_data);
        }
    }

    /**
     * 删除话题分类
     * @param $sid
     * @param $cid
     * @param $batch(批量删除为1)
     * @return array
     * @throws \think\Exception
     */
    public function deleteTopicCategory($sid, $cid, $batch = 0){
        //查询是否有话题使用此分类
        $where = [];
        $where['store_id'] = $sid;
        $where['catid'] = $batch == 1 ? ['in',$cid] : $cid;

        $info = db('system_news')->where($where)->find();
        if($info){
            return ['status' => 0, 'msg' => '有话题正在使用此分类，无法删除'];
        }

        $condition = [
            'store_id' => $sid,
            'cid' => $batch == 1 ? ['in',$cid] : $cid
        ];
        $result = db('system_columns')->where($condition)->setField('status', -1);
        return $result === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }



    /**
     * 后台获取分类列表
     * @param $sid
     * @param $type（all：获取所有；其余：分页获取）
     * @param $title
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getTopicCategoryList($sid, $type, $title, $p, $pageSize){
        $where = [];
        $where['store_id'] = $sid;
        $where['status'] = 1;

        if($type == 'all'){
            $field = 'cid,title';
            $list_count = db('system_columns')->where($where)->count();
            $list = db('system_columns')
                    ->field($field)
                    ->where($where)
                    ->order('cid DESC')
                    ->select();
        } else {
            $field = 'cid,title,thumb,description,ord';
            if(!empty($title)){
                $where['title'] = ['like', "%$title%"];
            }
            $list_count = db('system_columns')->where($where)->count();
            $list = db('system_columns')
                ->field($field)
                ->where($where)
                ->order('cid DESC')
                ->limit(($p -1)*$pageSize, $pageSize)
                ->select();
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 上传分类缩略图
     * @return array
     */
    public function uploadThumb(){
        $result = Upload::uploadFile();
        if($result == false){
            return ['status'=> 0, 'msg'=>'上传失败', 'data' => ''];
        }
        $img_url = Util::qiniu_url($result);
        $thumb_img_url = Util::small_qiniu_url($img_url);

        $data['content']['thumb_url'] = $thumb_img_url;

        return ['status'=> 1, 'msg'=>'上传成功', 'data' => $data];
    }


    /**
     * 获取推广详情
     * @param $sid
     * @return array
     */
    public function getCommonDetail($sid){
        $content['content'] = db('system_popularize')->where(['store_id' => $sid])->value('content');
        if(empty($content)){
            return ['status' => 0, 'msg' => '未找到相关内容'];
        } else {
            return ['status' => 1, 'msg' => '获取成功', 'data' => $content];
        }
    }

    /**
     * 保存推广详情
     * @param $sid
     * @param $content
     * @return int|string
     * @throws \think\Exception
     */
    public function saveCommonDetail($sid, $content){
        $info = db('system_popularize')->where(['store_id' => $sid])->find();
        if(empty($info)){
            //新增
            $data = [
                'store_id' => $sid,
                'content' => $content,
                'op_time' => time()
            ];
            return db('system_popularize')->insert($data);
        } else {
            //更新
            return db('system_popularize')->where(['store_id' => $sid])->update(['content' => $content, 'op_time' => time()]);
        }
    }
}







